#include "TimeoutManager.h"
#include "LoggerModule/Logger.h"
#include "DataStructures/DlmException.h"

TimeoutManager::~TimeoutManager()
{
	for(TimersMap::iterator ti = timers_.begin(); ti != timers_.end(); ++ti)
		timer_delete(ti->second);
}


void TimeoutManager::timeoutHandled(pid_t pid)
{
	timer_delete(timers_[pid]);
	timers_.erase(pid);
}


bool TimeoutManager::launchTimer(pid_t pid, int miliseconds)
{
	timer_t timer_id;
	struct sigevent sevp;
	struct itimerspec it;	
	
	sevp.sigev_notify = SIGEV_SIGNAL;		
	sevp.sigev_signo = TIMEOUT_SIG;
	sevp.sigev_value.sival_int = pid;
		
	it.it_value.tv_sec = miliseconds / 1000;
	it.it_value.tv_nsec = 1000000 * (miliseconds % 1000);	
	it.it_interval.tv_sec = 0;
	it.it_interval.tv_nsec = 0;	
			
	if(timer_create(CLOCK_REALTIME, &sevp, &timer_id) < 0)
	{	
		Logger::getInstance().logDlm(Logger::ERRNO, "Error creating timer for pid %d", pid);
		return false;
	}
	
	if(timer_settime(timer_id, 0, &it, NULL) < 0)
	{
		Logger::getInstance().logDlm(Logger::ERRNO, "Error launching timer for pid %d", pid);
		
		timer_delete(timer_id);
		return false;
	}	
	
	timers_[pid] = timer_id;
	
	return true;	
}
